package com.wyh.service.serviceImpl.gfiveImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyh.common.result.Result;
import com.wyh.domain.dto.gfive.LoginUser;
import com.wyh.domain.po.gfive.PageHelper;
import com.wyh.domain.po.gfive.Refund;
import com.wyh.service.gfive.RefundService;
import com.wyh.mapper.gfivemapper.RefundMapper;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;


import javax.annotation.Resource;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

/**
 * @author KmJHHhhhR
 * @description 针对表【refund(退款表)】的数据库操作Service实现
 * @createDate 2024-05-28 16:16:22
 */
@Service
public class RefundServiceImpl extends ServiceImpl<RefundMapper, Refund>
        implements RefundService {

    @Resource
    RefundMapper refundMapper;

    @Override
    public Result<Map<String, Object>> searchRefund(String custormerName, String customerPhone
            , LocalDateTime startTime, LocalDateTime endTime, PageHelper pageHelper) {
        QueryWrapper<Refund> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(Refund.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("refundbank")
                && !tableFieldInfo.getColumn().equals("refundreason")
        ).eq("state", 0);

        if (custormerName != null && !custormerName.isEmpty()) {
            queryWrapper.eq("customername", custormerName);
        }

        if (customerPhone != null && !customerPhone.isEmpty()) {
            queryWrapper.eq("`customerphone`", customerPhone);
        }

        if (startTime != null && endTime != null) {
            queryWrapper.between("applicationdate", startTime, endTime);
        } else if (startTime != null) {
            return Result.error("400", "缺少参数：结束时间");
        } else if (endTime != null) {
            return Result.error("400", "缺少参数：开始时间");
        }
        Page<Refund> page = new Page<>(pageHelper.getCurrentPage(), pageHelper.getPageSize());
        IPage<Refund> refundIPage = refundMapper.selectPage(page, queryWrapper);


        Map<String, Object> resultData = new HashMap<>();
        resultData.put("records", refundIPage.getRecords());
        resultData.put("current",refundIPage.getCurrent());
        resultData.put("pages",refundIPage.getPages());
        resultData.put("total", refundIPage.getTotal());

        return Result.success(resultData);

    }

    @Override
    public Result addRefundPic(int id, List<String> pictures, String receiptnumber) {

        Refund refund = refundMapper.selectById(id);

        if (refund == null) {
            return Result.error("退款记录不存在");
        }

        // 将图片列表转换为逗号分隔的字符串
        String picturesStr = null;

        if (pictures != null){
            picturesStr = String.join(";", pictures);
        }

        // 提交时获取当前时间
        LocalDateTime dateTime = LocalDateTime.now();
        ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());
        Instant instant = zonedDateTime.toInstant();
        Date date = Date.from(instant);

        //获取当前登录的用户名
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = loginUser.getUser().getName();

        refund.setState(1);
        refund.setPicture(picturesStr);
        refund.setHandledate(date);
        refund.setHandlepeople(name);
        refund.setReceiptnumber(receiptnumber);

        refundMapper.updateById(refund);


        return Result.success(refund);

    }


    @Override
    public Result<Map<String, Object>> selectRefund(String customerName, String customerPhone
            , LocalDateTime startTime, LocalDateTime endTime, PageHelper pageHelper) {


        QueryWrapper<Refund> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(Refund.class, tableFieldInfo -> !tableFieldInfo.getColumn().equals("refundbank")
                && !tableFieldInfo.getColumn().equals("refundreason")
        ).eq("state", 1);

        if (customerName != null && !customerName.isEmpty()) {
            queryWrapper.eq("customername", customerName);
        }

        if (customerPhone != null && !customerPhone.isEmpty()) {
            queryWrapper.eq("`customerphone`", customerPhone);
        }

        if (startTime != null && endTime != null) {
            queryWrapper.between("handledate", startTime, endTime);
        } else if (startTime != null) {
            return Result.error("400", "缺少参数：结束时间");
        } else if (endTime != null) {
            return Result.error("400", "缺少参数：开始时间");
        }

        Page<Refund> page = new Page<>(pageHelper.getCurrentPage(), pageHelper.getPageSize());
        IPage<Refund> refundIPage = refundMapper.selectPage(page, queryWrapper);


        Map<String, Object> resultData = new HashMap<>();
        resultData.put("records", refundIPage.getRecords());
        resultData.put("current",refundIPage.getCurrent());
        resultData.put("pages",refundIPage.getPages());
        resultData.put("total", refundIPage.getTotal());

        return Result.success(resultData);

    }

    @Override
    public Result getRefundPics(@RequestParam("id") int id) {
        Refund refund = refundMapper.selectById(id);

        if (refund == null) {
            return Result.error("退款记录不存在");
        }

        String picturesStr = refund.getPicture();
        List<String> pictureUrls = Arrays.asList(picturesStr.split(";"));

        return Result.success(pictureUrls);
    }
}




